<script setup>
import { onMounted, ref } from "vue";
import luckysheet from "luckysheet";
import LuckyExcel from "luckyexcel";
import AnalyesAPI from "@/api/system/analyes";
import dayjs from "dayjs";
import { useAnalysetStore } from "@/store/index";
import Index from "@/components/analysisSheetComponents/component/index.vue";
import indexPdf from "@/components/analysisSheetComponents/soil/tmpl83/indexPdf.vue";
import {
  filterValidSampleAdatas,
  transformData,
  filterValidSamples,
  getHeaders,
  splitDataIntoPages,
  processTableData,
} from "@/utils/method";
let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: "zh",
  autoCalculate: true,
  data: [
    {
      row: 9,
      celldata: [
        // 初始化表格数据，第一行包含表头
        { r: 0, c: 0, v: "样品编号" }, // A1
        { r: 0, c: 1, v: "湿样质量(g)" }, // B1
        { r: 0, c: 2, v: "干燥后样品质量(g)" }, // B1
        { r: 0, c: 3, v: ">10目筛的质量(g)" }, // B1
        { r: 0, c: 4, v: "过10目筛的质量(g)" }, // B1
        { r: 0, c: 5, v: "过筛目数/孔径（ ）" }, // B1
        { r: 0, c: 6, v: "样品重量 (g)" }, // B1
        { r: 0, c: 7, v: "检测项目  分析方法   浸提方法" }, // B1
        { r: 0, c: 8, v: "备注" }, // B1
      ], // 初始化数据
      config: {
        merge: {}, // 合并单元格
        columnlen: {
          // 设置列宽
          0: 130, // 第一列宽度 150px
          1: 130, // 第二列宽度 120px
          2: 130, // 第三列宽度 180px
          3: 130, // 第四列宽度 100px
          4: 130, // 第五列宽度 200px
          5: 130, // 第六列宽度 150px
          6: 130, // 第六列宽度 150px
          7: 200, // 第六列宽度 150px
          8: 130, // 第六列宽度 150px
        }, // 表格列宽
      },
    },
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([{ table: "仪器名称", id: 1 }]);
const waterForm = ref({
  adatas: {},
});
const analyseStatusPage = useAnalysetStore();
const record_sn = analyseStatusPage.waterForm.record_sn;
const checkDialogVisible = ref(false);
const processedData = ref([]);
const switchAB = ref(true);
const sheetData = ref("");
const jsonData = ref(null);
const checkTime = ref("");
const cdatas = ref([]);
// pdf显示隐藏
const showTargetPage = ref(false);
const tableHeaders = ref([]);
const tabler = ref([]);
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取初始数据并保存在响应式变量中
  getWaterCapacity();
  getMethod();
});

// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number; //任务名称
  // waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
  //   ? analyseStatusPage.waterForm.tableItem.test_method
  //   : analyseStatusPage.waterForm.tableItem.test_method_number; //分析方法
  // waterForm.value.category_id =
  //   analyseStatusPage.waterForm.tableItem.sample_category; // 样品类别

  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates;
};

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 25,
    record_sn: record_sn,
    // record_sn: 40,
  };
  AnalyesAPI.getAnalyseACapacity(josn).then((data) => {
    // console.log("获取水质容量 A单", data);
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data;
      sheetData.value = data.configs;
      options.data = sheetData.value;
      luckysheet.create(options);
      waterForm.value.unit =
        Array.isArray(data.unit) && data.unit.length === 0 ? {} : data.unit;
      //  样品类别
      waterForm.value.category_id = waterForm.value.category_id?.split(",");
      // zycontainer
      waterForm.value.zycontainer = waterForm.value.zycontainer?.split(",");
      // zytype
      waterForm.value.zytype = waterForm.value.zytype?.split(",");
      // ssztype
      waterForm.value.ssztype = waterForm.value.ssztype?.split(",");
      console.log(waterForm.value, "waterForm.value");
      processedData.value = data.adatas;
      //处理adata到pdf
      tableHeaders.value = splitDataIntoPages(data.adatas, 20);

      tabler.value = getHeaders(data.adatas, 23);
      console.log(tableHeaders.value, "tableHeaders.value");
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      };
    }
  });
};
const processDate = (data) => {
  if (!data || data.length < 3) {
    return [];
  }
  // 提取表头信息
  const header1 = data[0]
    .map((item) => item.value)
    .filter((value) => value !== null);
  console.log(header1);
  const header2 = data[1]
    .map((item) => item.value)
    .filter((value) => value !== null);
  const header3 = data[2]
    .map((item) => item.value)
    .filter((value) => value !== null);

  // waterForm.value.bdatas.dcwName.push(...header1.slice(1, 6));
  // waterForm.value.bdatas.jcx.push(...header2.slice(1, 6));

  // 提取数据行
  // const row = data[2].map(item => item.value);
  const rows = data
    .slice(3)
    .map((rowData) => rowData.map((item) => item.value));

  // 构建嵌套结构
  // 构建嵌套结构
  return rows.map((row) => {
    const result = header3.slice(0, 22).reduce((acc, key, index) => {
      acc[key] = row[index];
      return acc;
    }, {});
    result[header1[5]] = row[22]; // 额外的字段
    return result;
  });
};
const loadDataFromLocal = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  console.log(options.data);
  const data = options.data[0].data.map((row) => {
    return row
      .map((cell) => {
        return cell
          ? {
              field: cell.m || null,
              value: cell.v || null,
            }
          : null;
      })
      .filter((cell) => cell !== null); // 删除 null 值
  });
  console.log(data);
  // 调用函数
  processedData.value = processData(data);

  // 调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    // record_sn: record_sn,
    record_sn: 83,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
  }).then((data) => {
    console.log("调接口拿数据", data);
  });
};

const processData = (data) => {
  if (!data || data.length < 2) {
    return [];
  }

  // 提取表头
  const headers = data[0].map((item) => item.field || "");

  // 提取数据行
  const values = data[1].map((item) => item.value ?? null);

  // 构建结果
  const result = [];
  const rowObject = {};
  headers.forEach((header, index) => {
    if (header.trim()) {
      rowObject[header] = values[index] ?? null;
    }
  });

  result.push(rowObject);

  return result;
};

// 保存新增表单
const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map((row) => {
    return row
      .map((cell) => {
        return cell
          ? {
              field: cell.m || "默认字段",
              // field: cell.m || null,
              value: cell.v || null,
            }
          : null;
      })
      .filter((cell) => cell !== null); // 删除 null 值
  });

  processedData.value = filterValidSampleAdatas(processTableData(data));

  // cdatas.value = filterValidSamples(transformData(processedData.value));
  // console.log(cdatas.value);
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status;
    delete waterForm.value.reviewer_id;
  }

  waterForm.value.category_id = waterForm.value.category_id.join();
  // zycontainer
  waterForm.value.zycontainer = waterForm.value.zycontainer.join();
  // zytype
  waterForm.value.zytype = waterForm.value.zytype.join();

  // ssztype
  waterForm.value.ssztype = waterForm.value.ssztype.join();
  console.log(waterForm.value, "device");
  // waterForm.value.zycontainer = JSON.stringify(waterForm.value.zycontainer);
  // //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 75,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    // cdatas: cdatas.value,
  }).then((data) => {
    // console.log("调接口拿数据", data);
    ElMessage.success("保存成功");
    getWaterCapacity();
    switchAdd.value = false;
  });
};

function formatLuckysheetData(sheetData) {
  const formattedData = [];

  // 假设第一行为标题行
  const headers = sheetData[0].cells.map((cell) => cell.v);

  // 遍历每一行数据（从第二行开始）
  for (let i = 1; i < sheetData.length; i++) {
    const row = sheetData[i];
    const rowData = {};

    // 将每行的数据映射到对象属性
    row.cells.forEach((cell, index) => {
      rowData[headers[index]] = cell.v;
    });

    formattedData.push(rowData);
  }

  return formattedData;
}

// 用于获取最新的表格数据
const getUpdatedData = () => {
  checkDialogVisible.value = true;
};
const handleCheckClose = () => {
  checkDialogVisible.value = false;
};

// 确认提交校核
const handleSubmit = () => {
  console.log(checkTime.value);
  const formattedDate = checkTime.value
    ? dayjs(checkTime.value).format("YYYY-MM-DD")
    : "";
  console.log(analyseStatusPage.waterForm.id);
  AnalyesAPI.handleCheckTimeData({
    id: analyseStatusPage.waterForm.add_form_id,
    submit_date: formattedDate,
  }).then((data) => {
    if (data === 1) {
      ElMessage.success("提交成功！");
      checkDialogVisible.value = false;
    }
  });
};

// 上传文件
const loadExcel = (evt) => {
  const files = evt.target.files;
  console.log(files);
  if (files == null || files.length == 0) {
    alert("No files wait for import");
    return;
  }
  let name = files[0].name;
  let suffixArr = name.split("."),
    suffix = suffixArr[suffixArr.length - 1];
  if (suffix != "xlsx") {
    alert("Currently only supports the import of xlsx files");
    return;
  }
  LuckyExcel.transformExcelToLucky(
    files[0],
    function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert(
          "Failed to read the content of the excel file, currently does not support xls files!"
        );
        return;
      }
      console.log("exportJson", exportJson.sheets);
      jsonData.value = exportJson;

      luckysheet.destroy();
      luckysheet.create({
        container: "luckysheet", //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
      });
    }
  );
};

const handleSwitch = () => {
  switchAB.value = !switchAB.value;
};
// 下载
const downloadDetail = async () => {
  // console.log("下载");
  showTargetPage.value = true;
  await nextTick();
  window.print();
  setTimeout(() => {
    showTargetPage.value = false;
  }, 1000);
};
</script>

<template>
  <div class="card">
    <div v-show="!showTargetPage">
      <el-card class="box-card">
        <h1 style="text-align: center">土壤、固体废物 样品制备原始记录</h1>
        <div>SXLPHJ/JL/CX-22-83</div>
        <table class="table">
          <tr>
            <td colspan="2" style="width: 10%">任务编号</td>
            <td colspan="6" style="width: 7%">
              <el-input
                v-model="waterForm.task_name"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2" style="width: 7%">采样日期</td>
            <td colspan="2" style="width: 7%">
              <el-input
                v-model="waterForm.sampling_time"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="1" style="width: 7%">制样日期</td>
            <td colspan="5">
              <el-input
                v-model="waterForm.zyrq"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="2" style="width: 10%">样品类别</td>
            <td colspan="8">
              <el-checkbox-group v-model="waterForm.category_id">
                <el-checkbox label="土壤" value="土壤" />
                <el-checkbox label="固体废物" value="固体废物" />
                <el-checkbox label="其他" value="其他" />
                <!--              <el-input v-if="waterForm.category_id.includes('其他')" v-model="waterForm.otherCategory"-->
                <!--                        placeholder="请输入其他类别"/>-->
              </el-checkbox-group>
            </td>
            <td colspan="2">装样容器</td>
            <td colspan="8">
              <el-checkbox-group v-model="waterForm.zycontainer">
                <el-checkbox label="样品袋" value="样品袋" />
                <el-checkbox label="样品瓶" value="样品瓶" />
                <el-checkbox label="其他" value="其他" />
                <!--              <el-input v-if="waterForm.category_id.includes('其他')" v-model="waterForm.otherCategory"-->
                <!--                        placeholder="请输入其他类别"/>-->
              </el-checkbox-group>
            </td>
          </tr>
          <tr>
            <td colspan="2" rowspan="2">风干方式</td>
            <td colspan="2">
              <el-radio-group v-model="waterForm.fgtype">
                <el-radio label="自然风干" value="1" />
              </el-radio-group>
            </td>
            <td colspan="2">设备名称</td>
            <td colspan="2">设备型号</td>
            <td colspan="2">设备编号</td>
            <td colspan="2" rowspan="2">
              <el-checkbox-group v-model="waterForm.zytype">
                <el-checkbox label="研磨方式" value="1" />
                <el-checkbox label="破碎方式" value="2" />
              </el-checkbox-group>
            </td>
            <td colspan="1" style="width: 7%">
              <el-checkbox-group v-model="waterForm.ssztype">
                <el-checkbox label="手工" value="1" />
              </el-checkbox-group>
            </td>
            <td colspan="1" style="width: 7%">仪器名称</td>
            <td colspan="2" style="width: 10%">仪器型号</td>
            <td colspan="3">仪器编号</td>
          </tr>
          <tr>
            <td colspan="2">
              <el-radio-group v-model="waterForm.fgtype">
                <el-radio label="设备风干" value="2" />
              </el-radio-group>
            </td>
            <td colspan="2">
              <el-input
                v-model="waterForm.fg_device_name"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">
              <el-input
                v-model="waterForm.fg_device_model"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2">
              <el-input
                v-model="waterForm.fg_device_number"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="1" style="width: 7%">
              <el-checkbox-group v-model="waterForm.ssztype">
                <el-checkbox label="仪器" value="2" />
              </el-checkbox-group>
            </td>
            <td colspan="1" style="width: 7%">
              <el-input
                v-model="waterForm.device_name"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="2" style="width: 10%">
              <el-input
                v-model="waterForm.device_model"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="3">
              <el-input
                v-model="waterForm.device_number"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width: 100%; height: 500px" />
        <table class="table">
          <tr>
            <td style="width: 3%">备注</td>
            <td>
              <el-input
                v-model="waterForm.notes"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
        </table>
      </el-card>
    </div>
    <div v-show="showTargetPage">
      <indexPdf
        :waterForm="waterForm"
        :tableHeaders="tableHeaders"
        :tabler="tabler"
      />
    </div>
    <div v-show="!showTargetPage">
      <Index
        :water-form="waterForm"
        :handle-add-water-ph="handleAddWaterPh"
        :check-time="checkTime"
        :download-detail="downloadDetail"
        :switch-a-b="switchAB"
        :handle-switch="handleSwitch"
        :get-water-capacity="getWaterCapacity"
        :switch-add="switchAdd"
      />
    </div>
  </div>
</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
